<!--
 @description 搭配商品
 @fileName CollocationProduct.vue
 @author zengqiongying
 @created 2024/08/17 16:15:20
-->
<template>
  <div>
    <table-box
      ref="refTable"
      table-size="small"
      :data="list"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      :other-raw="otherRaws"
      :table-max-height="400"
      show-index
      :show-selection="false"
      :selected-arry.sync="tableSelected"
      :show-custom-setting="false"
      @selection-change="handleSelectionChange"
      @btnOperate="btnOperate"
    >
      <div slot="outerbtn-before" class="table-title">
        <span class="c-red">*</span>搭配商品：
      </div>
    </table-box>

    <add-product-dlg
      v-if="showAdd"
      multiple
      :visible.sync="showAdd"
      @change="handleAddChange"
    />

    <collocation-edit
      v-if="showEdit"
      :visible.sync="showEdit"
      :detail="activeRowData"
      @success="refreshTable"
    />
  </div>
</template>

<script>
import AddProductDlg from './AddProductDlg'
import CollocationEdit from './CollocationEdit'
import { parseTime } from '@/utils'
import { saveNotMainProduct, updateProductSort, deleteBatch } from '@/api/productCombine/detail'

export default {
  name: 'CollocationProduct',
  components: { AddProductDlg, CollocationEdit },
  props: {
    combineId: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const that = this
    return {
      sorting: false,
      sortTime: null,
      showEdit: false,
      showAdd: false,
      activeRowData: null,
      otherFilters: [],
      otherRaws: {},
      tableSelected: [],
      tableConfig: {
        interfacePath: null,
        tabIndex: 11,
        hideSearchBar: true,
        setting: [
          {
            prop: 'skuName',
            label: '搭配商品名称',
            minWidth: 200
          },
          {
            prop: 'mdmCode',
            label: '产品编码',
            minWidth: 200
          },
          {
            prop: 'mdmName',
            label: '产品名称',
            minWidth: 200
          },
          {
            prop: 'qty',
            label: '数量',
            minWidth: 100
          },
          {
            prop: 'discountMethod',
            label: '优惠方式',
            minWidth: 100,
            formatData: ({ discountMethod }) => {
              return [1, '1'].includes(discountMethod) ? '折扣' : [2, '2'].includes(discountMethod) ? '立减' : '无'
            }
          },
          {
            prop: 'discount',
            label: '优惠',
            minWidth: 100,
            formatData: ({ discount, discountMethod }) => {
              return `${discount || ''} ${[1, '1'].includes(discountMethod) ? '折' : [2, '2'].includes(discountMethod) ? '元' : ''}`
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 150,
            formatData: ({ createTime }) => {
              return parseTime(createTime, '{y}-{m}-{d} {h}:{i}:{s}')
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            width: 150,
            formatData: ({ createTime }) => {
              return parseTime(createTime, '{y}-{m}-{d} {h}:{i}:{s}')
            }
          },
          {
            prop: 'sort',
            label: '排序',
            width: 180,
            sortable: false,
            type: 'hidden',
            fixed: 'right',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'top')} class='my-button-txt'>置顶</el-button>)
              btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveUp')} class='my-button-txt'>上移</el-button>)
              btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveDown')} class='my-button-txt'>下移</el-button>)
              btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'bottom')} class='my-button-txt'>置底</el-button>)
              return _h('div', btns)
            }
          }
        ],
        btnList: [{
          buttonName: '添加搭配产品',
          optCode: 'add',
          outerFlag: true
        },
        {
          buttonName: '编辑',
          optCode: 'edit',
          outerFlag: true
        },
        {
          buttonName: '删除',
          optCode: 'del',
          outerFlag: true
        }]
      }
    }
  },

  computed: {},

  created() {},
  activated() {},

  mounted() {},

  methods: {
    // 刷新表格数据
    refreshTable(isInit) {
      // this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
      this.$emit('refresh')
    },
    handleSelectionChange(rows) {
      this.tableSelected = rows
    },
    btnOperate(code) {
      switch (code) {
        case 'add' :
          this.handleAdd()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'del' :
          if (!this.singleJudge(this.tableSelected, '删除', false)) {
            return
          }
          this.handleDelete(this.tableSelected[0])
          break
        default:
          break
      }
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型(bottom 置底 ，top 置顶 ， moveDown 下移 ，  moveUp 上移)
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      this.sorting = true
      const params = {
        id: row.id,
        type
      }
      updateProductSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    },
    handleAdd() {
      this.showAdd = true
    },
    handleEdit(row) {
      this.activeRowData = row && row.id ? row : {}
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    handleDelete() {
      this.$confirm('确定要删除当前所选商品吗？一旦删除，将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.tableSelected.map(v => v.id)
        deleteBatch(ids).then(res => {
          if (res.success === 1) {
            this.$message.success('操作成功')
            this.activeRowData = {}
            this.tableSelected = []
            this.refreshTable()
          }
        })
      })
    },
    handleAddChange(rows) {
      const skuIds = rows.map(v => v.id)
      const data = {
        productCombinationId: this.combineId,
        skuIds
      }
      saveNotMainProduct(data).then(res => {
        if (res.success === 1) {
          this.refreshTable()
        }
      })
    }

  }
}

</script>
<style lang='scss' scoped>
.my-button-txt{
  padding: 0 !important;
  color:$--color-primary;
}
/deep/ .function-box{
  .btn-box{
    width: 100%;
    display: flex;
    align-items: center;
    .table-title{
      margin-right: auto;
      margin-top: 20px;
      margin-bottom: 10px;
      line-height: 1.5;
      .c-red{
        color: #f00;
      }
    }
  }
}
</style>
